<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Http\Requests\ApiRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;


class OrderController extends Controller
{
    /**
     * 创建订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrder(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'server' => 'required',
            'game_id' => 'required',
            'product_version' => 'required',
            'ways_purchase' => 'required',
            'contact_details' => 'required'
        ], [
            'server.required' => '请选择服务器',
            'game_id.required' => '请填写游戏ID',
            'product_version.required' => '请选择商品版本',
            'ways_purchase.required' => '请选择购买方式',
            'contact_details.required' => '请填写联系方式',
        ]);
        if ($validator->fails()) {
            return response()->json(['code'=>"201","msg"=>$validator->errors()->first()]);
        }

        $server          = $request->input('server');
        $game_id         = $request->input('game_id');
        $product_version = $request->input('product_version');
        $ways_purchase   = $request->input('ways_purchase');
        $contact_details = $request->input('contact_details');

        $order = new Order();
        $order->order_id        = $this->createOrderId();
        $order->server          = $server;
        $order->game_id         = $game_id;
        $order->product_version = $product_version;
        $order->ways_purchase   = $ways_purchase;
        $order->contact_details = $contact_details;
        $order->status          = 0;

        if ($order->save())return response()->json(['code'=>"200","msg"=>'订单创建成功', 'data' => $order]);
    }

    /**
     * 生成订单号
     * @return string
     */
    protected function createOrderId()
    {
        $str = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $str;
    }
}
